package com.linuxrm.countdown.gaokao
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.widget.RemoteViews
import java.util.*
import android.view.View
class CountdownWidget : AppWidgetProvider() {
    companion object {
        private var handler: Handler? = null
        private var runnable: Runnable? = null
        private var isTimerRunning = false
        private var isRunning = false
    }
    override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray
    ) {
        super.onUpdate(context, appWidgetManager, appWidgetIds)
            appWidgetIds.forEach { appWidgetId ->
                updateAppWidget(context, appWidgetManager, appWidgetId)
        }
        if (!isTimerRunning) {
            stopTimer()
            startTimer(context, appWidgetManager, appWidgetIds)
            isTimerRunning = true
        }
    }
    private fun startTimer(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray
    ) {
        handler = Handler(Looper.getMainLooper())
        runnable = object : Runnable {
            override fun run() {
                appWidgetIds.forEach { appWidgetId ->
                    updateAppWidget(context, appWidgetManager, appWidgetId)
                }
                handler?.postDelayed(this, 1000)
            }
        }
        handler?.post(runnable!!)
    }
    private fun stopTimer() {
        handler?.removeCallbacks(runnable!!)
        runnable = null
    }
    fun updateAppWidget(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetId: Int
    ) {
        val views = RemoteViews(context.packageName, R.layout.widget_countdown)
        val intent = Intent(context, MainActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
        }
        val pendingIntent = android.app.PendingIntent.getActivity(
            context, 0, intent,
            android.app.PendingIntent.FLAG_UPDATE_CURRENT or android.app.PendingIntent.FLAG_IMMUTABLE
        )
        views.setOnClickPendingIntent(R.id.widget_container, pendingIntent)
        val gaokaoDate = CountdownLogic.getTargetDate(context)
        val currentTime = System.currentTimeMillis()
        views.setTextViewText(
            R.id.tv_current_datetime,
            CountdownLogic.dateFormat.format(Date(currentTime))
        )
        val diffMillis = gaokaoDate.timeInMillis - currentTime
        val days = diffMillis / (24 * 60 * 60 * 1000.0)
        val daysStr = String.format(Locale.CHINA, "%.5f", days)
        val fullText = "高考 $daysStr 天"
        views.setTextViewText(R.id.tv_countdown, fullText)
        views.setViewVisibility(R.id.tv_root, if (isRunning) View.GONE else View.VISIBLE)
        appWidgetManager.updateAppWidget(appWidgetId, views)
    }
    override fun onReceive(context: Context, intent: Intent) {
        super.onReceive(context, intent)
        val appWidgetManager = AppWidgetManager.getInstance(context)
        val thisWidget = ComponentName(context, CountdownWidget::class.java)
        val appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget)
        isRunning = CountdownLogic.isDaemonRunning(context)
        onUpdate(context, appWidgetManager, appWidgetIds)
    }
    override fun onDisabled(context: Context) {
        super.onDisabled(context)
        stopTimer()
        isTimerRunning = false
    }
}
